using System;
using UnityEngine;
using GGameFramework.Core.Pool;

namespace BangBangHell.Buttle
{
    /// <summary>
    /// 子弹基类（组件化设计）
    /// </summary>
    [RequireComponent(typeof(Rigidbody2D))]
    public abstract class BulletBase :  GameObjectPoolable
    {
        [Header("Base Settings")] [SerializeField]
        protected LayerMask _collisionMask;

        [SerializeField] protected float _baseDamage = 10f;
        [SerializeField] protected float _lifeTime = 5f;
        [SerializeField] protected ParticleSystem _impactVfx;
        [SerializeField] protected AudioClip _impactSfx;
        protected Transform _transform;
        protected Rigidbody2D _rigidbody;
        protected IBulletMovement _movementStrategy;
        protected IImpactHandler _impactHandler;
        protected float _currentLifeTime;
        protected bool _isActive;

        protected float _damageMultiplier = 1f;

        // 使用C#事件实现回调
        public event Action<BulletBase> OnBulletDisabled;

        public event Action<GameObject, float> OnDamageDealt;

        // 属性封装（保护数据）
        public float CalculatedDamage => _baseDamage * _damageMultiplier;
        public Vector2 Direction { get; protected set; }
        public GameObject Owner { get; private set; }

        protected virtual void Awake()
        {
            _transform = transform;
            _rigidbody = GetComponent<Rigidbody2D>();
            _rigidbody.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
        }

        /// <summary>
        /// 初始化子弹（对象池友好）
        /// </summary>
        public virtual void Initialize(GameObject owner, Vector2 direction,
            IBulletMovement movementStrategy = null,
            IImpactHandler impactHandler = null,
            float damageMultiplier = 1f)
        {
            Owner = owner;
            Direction = direction.normalized;
            _damageMultiplier = damageMultiplier;
            _currentLifeTime = _lifeTime;
            _isActive = true;
            // 策略模式注入
            _movementStrategy = movementStrategy ?? CreateDefaultMovement();
            _impactHandler = impactHandler ?? CreateDefaultImpactHandler();

            _movementStrategy.Initialize(_transform, HandleTargetReached);
        }

        protected virtual IBulletMovement CreateDefaultMovement()
        {
            // 默认直线移动策略
            return new LinearMovement(_rigidbody, 10f);
        }

        protected virtual IImpactHandler CreateDefaultImpactHandler()
        {
            // 默认伤害处理
            return new DamageImpactHandler();
        }

        protected virtual void Update()
        {
            if (!_isActive) return;

            _movementStrategy?.UpdateMovement();

            // 生命周期管理
            _currentLifeTime -= Time.deltaTime;
            if (_currentLifeTime <= 0)
            {
                Deactivate();
            }
        }

        protected virtual void OnTriggerEnter2D(Collider2D other)
        {
            if (!_isActive) return;
            if (_collisionMask.ContainsLayer(other.gameObject.layer))
            {
                HandleCollision(other);
            }
        }

        protected virtual void HandleCollision(Collider2D other)
        {
            _impactHandler?.HandleImpact(other, this);

            // 播放效果
            if (_impactVfx) Instantiate(_impactVfx, _transform.position, Quaternion.identity);
            if (_impactSfx) AudioSource.PlayClipAtPoint(_impactSfx, _transform.position);

            Deactivate();
        }

        protected virtual void HandleTargetReached()
        {
            // 用于跟踪子弹等特殊逻辑
            Deactivate();
        }

        public virtual void Deactivate()
        {
            _isActive = false;
            OnBulletDisabled?.Invoke(this);
            gameObject.SetActive(false);
        }

        // 对象池重置
        public virtual void OnPoolGet() => _isActive = true;
        public virtual void OnPoolRelease() => ResetState();

        protected virtual void ResetState()
        {
            _rigidbody.velocity = Vector2.zero;
            _rigidbody.angularVelocity = 0f;
            OnBulletDisabled = null;
        }

        public void TriggerDamageEvent(GameObject target, float damage)
        {
            OnDamageDealt?.Invoke(target, damage);
        }
    }

    /// <summary>
    /// 线性移动策略实现
    /// </summary>
    public class LinearMovement : IBulletMovement
    {
        private readonly Rigidbody2D _rigidbody;
        private readonly float _speed;
        private Transform _transform;
        private Action _onReachedTarget;

        public LinearMovement(Rigidbody2D rigidbody, float speed)
        {
            _rigidbody = rigidbody;
            _speed = speed;
        }

        public void Initialize(Transform transform, Action onReachedTarget = null)
        {
            _transform = transform;
            _onReachedTarget = onReachedTarget;
            _rigidbody.velocity = _transform.right * _speed;
        }

        public void UpdateMovement()
        {
            // 线性移动不需要每帧更新物理
        }
    }

    /// <summary>
    /// 默认伤害处理实现
    /// </summary>
    public class DamageImpactHandler : IImpactHandler
    {
        public void HandleImpact(Collider2D other, BulletBase bullet)
        {
            var damageable = other.GetComponent<IDamageable>();
            if (damageable != null)
            {
                float finalDamage = bullet.CalculatedDamage;
                damageable.TakeDamage(finalDamage);
                bullet.TriggerDamageEvent(other.gameObject, finalDamage);
            }
        }
    }

    // ======== 扩展工具 ========
    public static class LayerMaskExtensions
    {
        public static bool ContainsLayer(this LayerMask mask, int layer)
        {
            return mask == (mask | (1 << layer));
        }
    }

    public interface IDamageable
    {
        void TakeDamage(float amount);
    }
}